<script setup lang="ts">
import axios from "axios";
import {sha256} from "js-sha256";
import macros from "../../macros.ts";
import {router} from "../../main.js";
import {onBeforeMount, ref} from "vue"
var user:string;
var isUserExists=ref(true);
onBeforeMount(()=>{
  axios.get(macros.server+"/api/isuserexists").then(function (response){
    isUserExists.value=response.data.data;
  }).catch(function (error){
    alert(error);
    console.log(error);
  })
}
)

var password1:string;
var password2:string;


function submit(){
  var passwordHash:string;
  passwordHash=sha256(password1);
  if(password1!=password2){
    alert("两次输入的密码不匹配");
    throw "Password does not match!"
  }
  var userinfo= {
    username: user,
    password: passwordHash
  }
  axios.post(macros.server+"/api/adduser",userinfo).then(function (response){
    router.push("/admin");
  }).catch(function (error){
    alert(error);
    console.log(error);
  });
}
</script>

<template>
  <div v-if="isUserExists">
    <h1>用户已存在</h1>
  </div>
  <div v-else>
    <h2>请创建管理员账户</h2>
    <form style="width: 30rem;margin: auto"  class="input" method="post">
      <lable for="username" class="form-label text-light">用户名：</lable>
      <input v-model="user" type="text" class="form-control" id="username" placeholder="用户名" name="username">
      <br/>
      <lable for="password1" class="form-label text-light">密码：</lable>
      <input v-model="password1" type="password" class="form-control" id="password1" placeholder="密码" name="password1">
      <lable for="password2" class="form-label text-light">确认密码：</lable>
      <input v-model="password2" type="password" class="form-control" id="password2" placeholder="确认密码" name="password2">
      <p style="color: red" v-show="password1!=password2">两次输入的密码不匹配</p>
      <div style="text-align: center">
        <button @click="submit" type="button" class="btn btn-outline-light text-light" style="margin: 1rem">确认</button>
      </div>
    </form>
  </div>
</template>

<style scoped>

</style>